use crate::advanced_proxy::*;
use crate::builder::*;
use crate::client::*;
use crate::failover::*;
use async_trait::async_trait;
use rustcloud_core::{
    Request, Response, ServiceResult, ServiceError, ServiceInstance, ServiceRegistry,
    LoadBalancer, Transport, CircuitBreaker, ServiceProxy, CallStats, ProxyConfig,
    RetryConfig, TimeoutConfig, ConnectionPoolConfig, RetryCondition, RequestContext,
    CircuitBreakerState, ServiceWatcher, CircuitBreakerMetrics, StrategyInfo
};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tokio::sync::{RwLock, Mutex};
use serde_json;

// ==================== Mock 实现 ====================

/// Mock 服务注册中心
pub struct MockAdvancedRegistry {
    instances: Arc<Mutex<HashMap<String, Vec<ServiceInstance>>>>,
}

impl MockAdvancedRegistry {
    pub fn new() -> Self {
        Self {
            instances: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    pub async fn add_instance(&self, service_name: &str, instance: ServiceInstance) {
        let mut instances = self.instances.lock().await;
        instances.entry(service_name.to_string()).or_insert_with(Vec::new).push(instance);
    }

    pub async fn clear_instances(&self) {
        self.instances.lock().await.clear();
    }
}

#[async_trait]
impl ServiceRegistry for MockAdvancedRegistry {
    async fn register(&self, _instance: ServiceInstance) -> ServiceResult<()> {
        Ok(())
    }

    async fn deregister(&self, _instance: ServiceInstance) -> ServiceResult<()> {
        Ok(())
    }

    async fn discover(&self, service_name: &str) -> ServiceResult<Vec<ServiceInstance>> {
        let instances = self.instances.lock().await;
        Ok(instances.get(service_name).cloned().unwrap_or_default())
    }

    async fn health_check(&self, service_name: &str) -> ServiceResult<Vec<ServiceInstance>> {
        let instances = self.discover(service_name).await?;
        Ok(instances.into_iter().filter(|i| i.healthy).collect())
    }

    async fn watch(&self, _service_name: &str) -> ServiceResult<Box<dyn ServiceWatcher + Send>> {
        unimplemented!("Mock registry doesn't support watching")
    }
}

/// Mock 负载均衡器
pub struct MockAdvancedLoadBalancer {
    selection_index: Arc<Mutex<usize>>,
}

impl MockAdvancedLoadBalancer {
    pub fn new() -> Self {
        Self {
            selection_index: Arc::new(Mutex::new(0)),
        }
    }
}

#[async_trait]
impl LoadBalancer for MockAdvancedLoadBalancer {
    async fn select(&self, _service_name: &str, instances: &[ServiceInstance]) -> ServiceResult<Option<ServiceInstance>> {
        if instances.is_empty() {
            return Ok(None);
        }
        let mut index = self.selection_index.lock().await;
        let selected = instances.get(*index).cloned();
        *index = (*index + 1) % instances.len();
        Ok(selected)
    }

    fn name(&self) -> &str {
        "mock_advanced_load_balancer"
    }

    fn get_strategy_info(&self) -> StrategyInfo {
        StrategyInfo {
            name: "Mock Advanced Load Balancer".to_string(),
            description: "Mock load balancer for testing".to_string(),
            requires_session_affinity: false,
            supports_weighted_routing: false,
        }
    }
}

/// Mock 传输层
pub struct MockAdvancedTransport {
    responses: Arc<Mutex<HashMap<String, Response>>>,
    call_count: Arc<Mutex<usize>>,
    should_fail: Arc<Mutex<bool>>,
    delay: Arc<Mutex<Option<Duration>>>,
}

impl MockAdvancedTransport {
    pub fn new() -> Self {
        Self {
            responses: Arc::new(Mutex::new(HashMap::new())),
            call_count: Arc::new(Mutex::new(0)),
            should_fail: Arc::new(Mutex::new(false)),
            delay: Arc::new(Mutex::new(None)),
        }
    }

    pub async fn set_response(&self, path: &str, response: Response) {
        self.responses.lock().await.insert(path.to_string(), response);
    }

    pub async fn set_should_fail(&self, should_fail: bool) {
        *self.should_fail.lock().await = should_fail;
    }

    pub async fn set_delay(&self, delay: Option<Duration>) {
        *self.delay.lock().await = delay;
    }

    pub async fn get_call_count(&self) -> usize {
        *self.call_count.lock().await
    }

    pub async fn reset_call_count(&self) {
        *self.call_count.lock().await = 0;
    }
}

#[async_trait]
impl Transport for MockAdvancedTransport {
    async fn send(&self, request: Request, _instance: &ServiceInstance) -> ServiceResult<Response> {
        *self.call_count.lock().await += 1;

        // 模拟延迟
        if let Some(delay) = *self.delay.lock().await {
            tokio::time::sleep(delay).await;
        }

        if *self.should_fail.lock().await {
            return Err(ServiceError::NetworkError("Mock transport failure".to_string()));
        }

        let responses = self.responses.lock().await;
        if let Some(response) = responses.get(&request.path) {
            Ok(response.clone())
        } else {
            let mut response = Response::new(200);
            response.set_body(format!("Mock response for {}", request.path).as_bytes().to_vec());
            Ok(response)
        }
    }

    async fn send_batch(&self, requests: Vec<(Request, &ServiceInstance)>) -> Vec<ServiceResult<Response>> {
        let mut results = Vec::new();
        for (request, instance) in requests {
            results.push(self.send(request, instance).await);
        }
        results
    }

    fn name(&self) -> &str {
        "mock_advanced_transport"
    }
}

/// Mock 熔断器
pub struct MockAdvancedCircuitBreaker {
    state: Arc<Mutex<CircuitBreakerState>>,
    call_count: Arc<Mutex<usize>>,
}

impl MockAdvancedCircuitBreaker {
    pub fn new() -> Self {
        Self {
            state: Arc::new(Mutex::new(CircuitBreakerState::Closed)),
            call_count: Arc::new(Mutex::new(0)),
        }
    }

    pub async fn set_state(&self, state: CircuitBreakerState) {
        *self.state.lock().await = state;
    }

    pub async fn get_call_count(&self) -> usize {
        *self.call_count.lock().await
    }
}

#[async_trait]
impl CircuitBreaker for MockAdvancedCircuitBreaker {
    async fn call(
        &self,
        service_name: &str,
        func: Box<dyn FnOnce() -> std::pin::Pin<Box<dyn std::future::Future<Output = ServiceResult<Response>> + Send>> + Send>,
    ) -> ServiceResult<Response> {
        *self.call_count.lock().await += 1;

        match *self.state.lock().await {
            CircuitBreakerState::Open => {
                Err(ServiceError::CircuitBreakerOpen(service_name.to_string()))
            }
            _ => func().await,
        }
    }

    async fn call_with_fallback<T, F, Fut, FB>(
        &self,
        service_name: &str,
        operation: F,
        fallback: FB,
    ) -> ServiceResult<T>
    where
        T: Send + 'static,
        F: FnOnce() -> Fut + Send,
        Fut: std::future::Future<Output = ServiceResult<T>> + Send,
        FB: FnOnce() -> T + Send,
    {
        // 由于call方法的签名不匹配，这里简化实现
        match *self.state.lock().await {
            CircuitBreakerState::Open => Ok(fallback()),
            _ => operation().await.or_else(|_| Ok(fallback())),
        }
    }

    async fn state(&self, _service_name: &str) -> CircuitBreakerState {
        *self.state.lock().await
    }

    async fn metrics(&self, _service_name: &str) -> CircuitBreakerMetrics {
        CircuitBreakerMetrics {
            total_calls: *self.call_count.lock().await as u64,
            failed_calls: 0,
            success_calls: *self.call_count.lock().await as u64,
            last_failure_time: None,
            state: *self.state.lock().await,
        }
    }

    async fn reset(&self, _service_name: &str) -> ServiceResult<()> {
        *self.state.lock().await = CircuitBreakerState::Closed;
        Ok(())
    }

    async fn force_open(&self, _service_name: &str) -> ServiceResult<()> {
        *self.state.lock().await = CircuitBreakerState::Open;
        Ok(())
    }

    async fn force_close(&self, _service_name: &str) -> ServiceResult<()> {
        *self.state.lock().await = CircuitBreakerState::Closed;
        Ok(())
    }
}

// ==================== 测试拦截器 ====================

/// 测试请求拦截器
pub struct TestRequestInterceptor {
    name: String,
    order: i32,
    execution_count: Arc<Mutex<usize>>,
    should_fail: Arc<Mutex<bool>>,
}

impl TestRequestInterceptor {
    pub fn new(name: &str, order: i32) -> Self {
        Self {
            name: name.to_string(),
            order,
            execution_count: Arc::new(Mutex::new(0)),
            should_fail: Arc::new(Mutex::new(false)),
        }
    }

    pub async fn set_should_fail(&self, should_fail: bool) {
        *self.should_fail.lock().await = should_fail;
    }

    pub async fn get_execution_count(&self) -> usize {
        *self.execution_count.lock().await
    }
}

#[async_trait]
impl RequestInterceptor for TestRequestInterceptor {
    async fn before_request(&self, request: &mut Request, _context: &RequestContext) -> ServiceResult<()> {
        *self.execution_count.lock().await += 1;

        if *self.should_fail.lock().await {
            return Err(ServiceError::NetworkError(format!("Interceptor {} failed", self.name)));
        }

        // 添加测试头部
        request.headers.insert(
            format!("X-Interceptor-{}", self.name),
            format!("executed-{}", self.get_execution_count().await),
        );
        Ok(())
    }

    fn name(&self) -> &str {
        &self.name
    }

    fn order(&self) -> i32 {
        self.order
    }
}

/// 测试响应拦截器
pub struct TestResponseInterceptor {
    name: String,
    order: i32,
    execution_count: Arc<Mutex<usize>>,
    error_count: Arc<Mutex<usize>>,
}

impl TestResponseInterceptor {
    pub fn new(name: &str, order: i32) -> Self {
        Self {
            name: name.to_string(),
            order,
            execution_count: Arc::new(Mutex::new(0)),
            error_count: Arc::new(Mutex::new(0)),
        }
    }

    pub async fn get_execution_count(&self) -> usize {
        *self.execution_count.lock().await
    }

    pub async fn get_error_count(&self) -> usize {
        *self.error_count.lock().await
    }
}

#[async_trait]
impl ResponseInterceptor for TestResponseInterceptor {
    async fn after_response(&self, _request: &Request, response: &mut Response, _context: &RequestContext) -> ServiceResult<()> {
        *self.execution_count.lock().await += 1;

        // 添加测试头部
        response.headers.insert(
            format!("X-Response-Interceptor-{}", self.name),
            format!("executed-{}", self.get_execution_count().await),
        );
        Ok(())
    }

    async fn on_error(&self, _request: &Request, _error: &ServiceError, _context: &RequestContext) -> ServiceResult<()> {
        *self.error_count.lock().await += 1;
        Ok(())
    }

    fn name(&self) -> &str {
        &self.name
    }

    fn order(&self) -> i32 {
        self.order
    }
}

// ==================== 辅助函数 ====================

fn create_test_config() -> ProxyConfig {
    ProxyConfig {
        retry: RetryConfig {
            max_attempts: 3,
            base_delay: Duration::from_millis(10),
            max_delay: Duration::from_millis(100),
            retry_on: vec![RetryCondition::NetworkError, RetryCondition::Timeout],
            budget_percent: 10.0,
        },
        timeout: TimeoutConfig {
            connect_timeout: Duration::from_millis(100),
            request_timeout: Duration::from_millis(500),
            idle_timeout: Duration::from_secs(30),
        },
        connection_pool: ConnectionPoolConfig {
            max_connections: 10,
            max_idle_connections: 5,
            connection_timeout: Duration::from_millis(100),
            idle_timeout: Duration::from_secs(30),
            keep_alive: true,
        },
        circuit_breaker: None,
    }
}

fn create_test_proxy() -> AdvancedClientProxy {
    let registry = Arc::new(MockAdvancedRegistry::new());
    let load_balancer = Arc::new(MockAdvancedLoadBalancer::new());
    let transport = Arc::new(MockAdvancedTransport::new());
    let circuit_breaker = Arc::new(MockAdvancedCircuitBreaker::new());
    let config = create_test_config();

    AdvancedClientProxy::new(registry, load_balancer, transport, circuit_breaker, config)
}

fn create_test_proxy_with_mocks(
    registry: Arc<MockAdvancedRegistry>,
    transport: Arc<MockAdvancedTransport>,
) -> AdvancedClientProxy {
    let load_balancer = Arc::new(MockAdvancedLoadBalancer::new());
    let circuit_breaker = Arc::new(MockAdvancedCircuitBreaker::new());
    let config = create_test_config();

    AdvancedClientProxy::new(registry, load_balancer, transport, circuit_breaker, config)
}

// ==================== 基础功能测试 ====================

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_advanced_proxy_creation() {
        let proxy = create_test_proxy();
        
        // 验证代理能够正常创建
        let stats = proxy.get_call_stats().await;
        assert_eq!(stats.total_calls, 0);
        assert_eq!(stats.successful_calls, 0);
        assert_eq!(stats.failed_calls, 0);
    }

    #[tokio::test]
    async fn test_request_interceptor_execution() {
        let proxy = create_test_proxy();
        
        // 添加测试拦截器
        let interceptor1 = Arc::new(TestRequestInterceptor::new("test1", 1));
        let interceptor2 = Arc::new(TestRequestInterceptor::new("test2", 2));
        
        proxy.add_request_interceptor(interceptor1.clone()).await;
        proxy.add_request_interceptor(interceptor2.clone()).await;
        
        // 设置服务实例
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        let proxy = create_test_proxy_with_mocks(registry, transport.clone());
        proxy.add_request_interceptor(interceptor1.clone()).await;
        proxy.add_request_interceptor(interceptor2.clone()).await;
        
        let request = Request::new("test-service", "GET", "/test");
        let _result = proxy.call_with_retry(request).await;
        
        // 验证拦截器执行
        assert_eq!(interceptor1.get_execution_count(), 1);
        assert_eq!(interceptor2.get_execution_count(), 1);
    }

    #[tokio::test]
    async fn test_response_interceptor_execution() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        let proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        // 添加响应拦截器
        let interceptor = Arc::new(TestResponseInterceptor::new("test", 1));
        proxy.add_response_interceptor(interceptor.clone()).await;
        
        let request = Request::new("test-service", "GET", "/test");
        let result = proxy.call_with_retry(request).await;
        
        assert!(result.is_ok());
        assert_eq!(interceptor.get_execution_count(), 1);
    }

    #[tokio::test]
    async fn test_interceptor_order() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        let proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        // 按不同顺序添加拦截器
        let interceptor_high = Arc::new(TestRequestInterceptor::new("high", 1));
        let interceptor_low = Arc::new(TestRequestInterceptor::new("low", 10));
        
        // 故意颠倒添加顺序
        proxy.add_request_interceptor(interceptor_low.clone()).await;
        proxy.add_request_interceptor(interceptor_high.clone()).await;
        
        let request = Request::new("test-service", "GET", "/test");
        let _result = proxy.call_with_retry(request).await;
        
        // 验证高优先级拦截器先执行
        assert_eq!(interceptor_high.get_execution_count(), 1);
        assert_eq!(interceptor_low.get_execution_count(), 1);
    }

    #[tokio::test]
    async fn test_retry_mechanism() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        // 设置传输失败
        transport.set_should_fail(true);
        
        let proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        let request = Request::new("test-service", "GET", "/test");
        let result = proxy.call_with_retry(request).await;
        
        // 应该失败，但会重试
        assert!(result.is_err());
        assert_eq!(transport.get_call_count(), 3); // 初始调用 + 2次重试
    }

    #[tokio::test]
    async fn test_successful_retry() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        let proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        // 设置第一次失败，然后成功
        transport.set_should_fail(true);
        tokio::spawn({
            let transport = transport.clone();
            async move {
                tokio::time::sleep(Duration::from_millis(20)).await;
                transport.set_should_fail(false);
            }
        });
        
        let request = Request::new("test-service", "GET", "/test");
        let result = proxy.call_with_retry(request).await;
        
        // 最终应该成功
        assert!(result.is_ok());
        assert!(transport.get_call_count() >= 1);
    }

    #[tokio::test]
    async fn test_cache_functionality() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        let mut proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        // 启用缓存
        let cache_config = CacheConfig {
            enabled: true,
            strategy: CacheStrategy::TimeBasedCache { ttl: Duration::from_secs(60) },
            compress: false,
            serialize_format: "json".to_string(),
        };
        proxy = proxy.with_cache_config(cache_config);
        
        // 设置特定响应
        let mut response = Response::new(200);
        response.set_body(b"cached response".to_vec());
        transport.set_response("/cache-test", response);
        
        let request1 = Request::new("test-service", "GET", "/cache-test");
        let result1 = proxy.call_with_retry(request1).await;
        assert!(result1.is_ok());
        assert_eq!(transport.get_call_count(), 1);
        
        // 第二次相同请求应该使用缓存
        let request2 = Request::new("test-service", "GET", "/cache-test");
        let result2 = proxy.call_with_retry(request2).await;
        assert!(result2.is_ok());
        assert_eq!(transport.get_call_count(), 1); // 没有额外调用
        
        // 验证缓存统计
        let (total_entries, expired_entries) = proxy.get_cache_stats().await;
        assert!(total_entries > 0);
        assert_eq!(expired_entries, 0);
    }

    #[tokio::test]
    async fn test_cache_expiration() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        let mut proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        // 启用短期缓存
        let cache_config = CacheConfig {
            enabled: true,
            strategy: CacheStrategy::TimeBasedCache { ttl: Duration::from_millis(50) },
            compress: false,
            serialize_format: "json".to_string(),
        };
        proxy = proxy.with_cache_config(cache_config);
        
        let request1 = Request::new("test-service", "GET", "/expire-test");
        let _result1 = proxy.call_with_retry(request1).await;
        assert_eq!(transport.get_call_count(), 1);
        
        // 等待缓存过期
        tokio::time::sleep(Duration::from_millis(100)).await;
        
        let request2 = Request::new("test-service", "GET", "/expire-test");
        let _result2 = proxy.call_with_retry(request2).await;
        assert_eq!(transport.get_call_count(), 2); // 缓存过期，重新调用
    }

    #[tokio::test]
    async fn test_concurrent_requests() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        let proxy = Arc::new(create_test_proxy_with_mocks(registry, transport.clone()));
        
        // 并发发送多个请求
        let mut handles = Vec::new();
        for i in 0..5 {
            let proxy_clone = proxy.clone();
            let handle = tokio::spawn(async move {
                let request = Request::new("test-service", "GET", &format!("/concurrent-{}", i));
                proxy_clone.call_with_retry(request).await
            });
            handles.push(handle);
        }
        
        // 等待所有请求完成
        let mut success_count = 0;
        for handle in handles {
            if handle.await.unwrap().is_ok() {
                success_count += 1;
            }
        }
        
        assert_eq!(success_count, 5);
        assert_eq!(transport.get_call_count(), 5);
    }

    #[tokio::test]
    async fn test_connection_pool_limits() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        // 设置延迟以模拟慢请求
        transport.set_delay(Some(Duration::from_millis(100)));
        
        let proxy = Arc::new(create_test_proxy_with_mocks(registry, transport.clone()));
        
        // 发送超过连接池限制的并发请求
        let mut handles = Vec::new();
        for i in 0..15 { // 超过max_connections=10
            let proxy_clone = proxy.clone();
            let handle = tokio::spawn(async move {
                let request = Request::new("test-service", "GET", &format!("/pool-{}", i));
                proxy_clone.call_with_retry(request).await
            });
            handles.push(handle);
        }
        
        // 等待部分请求完成
        let mut completed_count = 0;
        for handle in handles {
            if handle.await.unwrap().is_ok() {
                completed_count += 1;
            }
        }
        
        // 验证连接池限制生效
        assert!(completed_count <= 15);
    }

    #[tokio::test]
    async fn test_connection_statistics() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        let proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        // 发送几个成功请求
        for i in 0..3 {
            let request = Request::new("test-service", "GET", &format!("/stats-{}", i));
            let _result = proxy.call_with_retry(request).await;
        }
        
        // 发送一个失败请求
        transport.set_should_fail(true);
        let request = Request::new("test-service", "GET", "/stats-fail");
        let _result = proxy.call_with_retry(request).await;
        
        // 检查统计信息
        let stats = proxy.get_service_stats("test-service").await;
        assert!(stats.is_some());
        
        let stats = stats.unwrap();
        assert!(stats.total_requests >= 4);
        assert!(stats.successful_requests >= 3);
        assert!(stats.failed_requests >= 1);
        assert!(stats.last_request_time.is_some());
    }

    #[tokio::test]
    async fn test_batch_calls() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        let proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        // 准备批量请求
        let requests = vec![
            Request::new("test-service", "GET", "/batch-1"),
            Request::new("test-service", "GET", "/batch-2"),
            Request::new("test-service", "GET", "/batch-3"),
        ];
        
        let results = proxy.batch_call(requests).await;
        
        // 验证批量调用结果
        assert_eq!(results.len(), 3);
        for result in results {
            assert!(result.is_ok());
        }
        
        assert_eq!(transport.get_call_count(), 3);
    }

    #[tokio::test]
    async fn test_circuit_breaker_integration() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        let circuit_breaker = Arc::new(MockAdvancedCircuitBreaker::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        // 创建带熔断器的代理
        let load_balancer = Arc::new(MockAdvancedLoadBalancer::new());
        let config = create_test_config();
        let proxy = AdvancedClientProxy::new(
            registry,
            load_balancer,
            transport.clone(),
            circuit_breaker.clone(),
            config,
        );
        
        // 正常调用
        let request = Request::new("test-service", "GET", "/circuit-test");
        let result = proxy.call_with_retry(request).await;
        assert!(result.is_ok());
        assert_eq!(circuit_breaker.get_call_count(), 1);
        
        // 设置熔断器为打开状态
        circuit_breaker.set_state(CircuitBreakerState::Open);
        
        let request = Request::new("test-service", "GET", "/circuit-test-2");
        let result = proxy.call_with_retry(request).await;
        assert!(result.is_err());
        
        // 验证错误类型
        match result.unwrap_err() {
            ServiceError::CircuitBreakerOpen(_) => {}, // 期望的错误
            e => panic!("Expected CircuitBreakerOpen error, got {:?}", e),
        }
    }

    #[tokio::test]
    async fn test_interceptor_error_handling() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        let proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        // 添加会失败的拦截器
        let failing_interceptor = Arc::new(TestRequestInterceptor::new("failing", 1));
        failing_interceptor.set_should_fail(true);
        proxy.add_request_interceptor(failing_interceptor.clone()).await;
        
        let request = Request::new("test-service", "GET", "/error-test");
        let result = proxy.call_with_retry(request).await;
        
        // 拦截器失败应该导致整个请求失败
        assert!(result.is_err());
        assert_eq!(failing_interceptor.get_execution_count(), 1);
        assert_eq!(transport.get_call_count(), 0); // 请求没有到达传输层
    }

    #[tokio::test]
    async fn test_error_interceptor_execution() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        // 设置传输失败
        transport.set_should_fail(true);
        
        let proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        // 添加响应拦截器
        let error_interceptor = Arc::new(TestResponseInterceptor::new("error", 1));
        proxy.add_response_interceptor(error_interceptor.clone()).await;
        
        let request = Request::new("test-service", "GET", "/error-intercept-test");
        let result = proxy.call_with_retry(request).await;
        
        // 请求应该失败
        assert!(result.is_err());
        
        // 错误拦截器应该被调用
        assert!(error_interceptor.get_error_count() > 0);
    }

    #[tokio::test]
    async fn test_request_timeout() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        // 设置长延迟以触发超时
        transport.set_delay(Some(Duration::from_secs(1)));
        
        let proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        let request = Request::new("test-service", "GET", "/timeout-test");
        let result = proxy.call_with_retry(request).await;
        
        // 应该超时失败
        assert!(result.is_err());
        match result.unwrap_err() {
            ServiceError::TimeoutError(_) => {}, // 期望的超时错误
            e => panic!("Expected TimeoutError, got {:?}", e),
        }
    }

    #[tokio::test]
    async fn test_no_available_instances() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        // 不添加任何服务实例
        
        let proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        let request = Request::new("nonexistent-service", "GET", "/test");
        let result = proxy.call_with_retry(request).await;
        
        // 应该返回无可用实例错误
        assert!(result.is_err());
        match result.unwrap_err() {
            ServiceError::NoAvailableInstances(service) => {
                assert_eq!(service, "nonexistent-service");
            }
            e => panic!("Expected NoAvailableInstances error, got {:?}", e),
        }
        
        // 传输层不应该被调用
        assert_eq!(transport.get_call_count(), 0);
    }

    #[tokio::test]
    async fn test_cache_cleanup() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        let mut proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        // 启用短期缓存
        let cache_config = CacheConfig {
            enabled: true,
            strategy: CacheStrategy::TimeBasedCache { ttl: Duration::from_millis(10) },
            compress: false,
            serialize_format: "json".to_string(),
        };
        proxy = proxy.with_cache_config(cache_config);
        
        // 发送请求以填充缓存
        let request = Request::new("test-service", "GET", "/cleanup-test");
        let _result = proxy.call_with_retry(request).await;
        
        let (total_before, _) = proxy.get_cache_stats().await;
        assert!(total_before > 0);
        
        // 等待缓存过期
        tokio::time::sleep(Duration::from_millis(50)).await;
        
        // 清理过期缓存
        proxy.cleanup_expired_cache().await;
        
        let (total_after, _) = proxy.get_cache_stats().await;
        assert!(total_after < total_before || total_after == 0);
    }

    #[tokio::test]
    async fn test_lru_cache_eviction() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        let mut proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        // 启用LRU缓存，最大2个条目
        let cache_config = CacheConfig {
            enabled: true,
            strategy: CacheStrategy::LruCache { max_size: 2, ttl: Duration::from_secs(60) },
            compress: false,
            serialize_format: "json".to_string(),
        };
        proxy = proxy.with_cache_config(cache_config);
        
        // 发送3个不同的请求
        for i in 1..=3 {
            let request = Request::new("test-service", "GET", &format!("/lru-{}", i));
            let _result = proxy.call_with_retry(request).await;
        }
        
        let (total_entries, _) = proxy.get_cache_stats().await;
        assert!(total_entries <= 2); // LRU eviction should limit cache size
        assert_eq!(transport.get_call_count(), 3); // All requests should hit transport
    }

    // ==================== 构建器模式测试 ====================

    #[tokio::test]
    async fn test_advanced_proxy_builder() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let load_balancer = Arc::new(MockAdvancedLoadBalancer::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        let circuit_breaker = Arc::new(MockAdvancedCircuitBreaker::new());
        
        let builder = AdvancedProxyBuilder::new("test-service".to_string())
            .registry(registry.clone())
            .load_balancer(load_balancer)
            .transport(transport)
            .circuit_breaker(circuit_breaker);
        
        let proxy = builder.build().await;
        assert!(proxy.is_ok());
        
        let proxy = proxy.unwrap();
        let stats = proxy.get_call_stats().await;
        assert_eq!(stats.total_calls, 0);
    }

    #[tokio::test]
    async fn test_builder_missing_components() {
        let builder = AdvancedProxyBuilder::new("test-service".to_string());
        
        // 缺少组件的构建应该失败
        let result = builder.build().await;
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Registry required"));
    }

    #[tokio::test]
    async fn test_builder_with_default_interceptors() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let load_balancer = Arc::new(MockAdvancedLoadBalancer::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        let circuit_breaker = Arc::new(MockAdvancedCircuitBreaker::new());
        
        registry.add_instance("test-service", ServiceInstance::new("test-service", "localhost", 8080, "http"));
        
        let proxy = AdvancedProxyBuilder::new("test-service".to_string())
            .registry(registry)
            .load_balancer(load_balancer)
            .transport(transport.clone())
            .circuit_breaker(circuit_breaker)
            .build()
            .await
            .unwrap();
        
        // 测试默认拦截器是否正常工作
        let request = Request::new("test-service", "GET", "/builder-test");
        let result = proxy.call_with_retry(request).await;
        assert!(result.is_ok());
        assert_eq!(transport.get_call_count(), 1);
    }

    // ==================== 故障转移测试 ====================

    #[tokio::test]
    async fn test_intelligent_retry_manager() {
        let retry_manager = IntelligentRetryManager::new(
            FailoverStrategy::FastFailover,
            vec![RetryCondition::NetworkError],
            3,
            Duration::from_millis(10),
            Duration::from_millis(100),
        );
        
        // 测试重试条件判断
        let network_error = ServiceError::NetworkError("Test error".to_string());
        assert!(retry_manager.should_retry(&network_error, None, 1));
        assert!(!retry_manager.should_retry(&network_error, None, 4)); // 超过最大重试次数
        
        // 测试非重试错误
        let other_error = ServiceError::ServiceUnavailable("Service down".to_string());
        assert!(!retry_manager.should_retry(&other_error, None, 1));
    }

    #[tokio::test]
    async fn test_failover_strategy_fast_failover() {
        let strategy = FailoverStrategy::FastFailover;
        let instances = vec![
            ServiceInstance::new("service", "host1", 8080, "http"),
            ServiceInstance::new("service", "host2", 8080, "http"),
            ServiceInstance::new("service", "host3", 8080, "http"),
        ];
        
        let selected = strategy.select_instance(&instances, &HashMap::new());
        assert!(selected.is_some());
        assert!(instances.contains(selected.unwrap()));
    }

    #[tokio::test]
    async fn test_failover_strategy_gradual_degradation() {
        let strategy = FailoverStrategy::GradualDegradation;
        let instances = vec![
            ServiceInstance::new("service", "host1", 8080, "http"),
            ServiceInstance::new("service", "host2", 8080, "http"),
        ];
        
        let selected = strategy.select_instance(&instances, &HashMap::new());
        assert!(selected.is_some());
    }

    #[tokio::test]
    async fn test_failover_strategy_sticky_session() {
        let strategy = FailoverStrategy::StickySession;
        let instances = vec![
            ServiceInstance::new("service", "host1", 8080, "http"),
            ServiceInstance::new("service", "host2", 8080, "http"),
        ];
        
        let selected = strategy.select_instance(&instances, &HashMap::new());
        assert!(selected.is_some());
    }

    #[tokio::test]
    async fn test_failover_strategy_zone_aware() {
        let strategy = FailoverStrategy::ZoneAware;
        let instances = vec![
            ServiceInstance::new("service", "host1", 8080, "http"),
            ServiceInstance::new("service", "host2", 8080, "http"),
        ];
        
        let selected = strategy.select_instance(&instances, &HashMap::new());
        assert!(selected.is_some());
    }

    #[tokio::test]
    async fn test_instance_stats_tracking() {
        let retry_manager = IntelligentRetryManager::new(
            FailoverStrategy::FastFailover,
            vec![RetryCondition::NetworkError],
            3,
            Duration::from_millis(10),
            Duration::from_millis(100),
        );
        
        let instance = ServiceInstance::new("service", "host1", 8080, "http");
        
        // 记录成功
        retry_manager.record_success(&instance).await;
        
        // 记录失败
        let error = ServiceError::NetworkError("Test failure".to_string());
        retry_manager.record_failure(&instance, &error).await;
        
        // 检查统计信息
        let stats = retry_manager.get_instance_stats(&instance).await;
        assert!(stats.is_some());
        
        let stats = stats.unwrap();
        assert_eq!(stats.total_requests, 2);
        assert_eq!(stats.successful_requests, 1);
        assert_eq!(stats.failed_requests, 1);
    }

    // ==================== 综合集成测试 ====================

    #[tokio::test]
    async fn test_full_advanced_proxy_workflow() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        
        // 添加多个服务实例
        registry.add_instance("test-service", ServiceInstance::new("test-service", "host1", 8080, "http"));
        registry.add_instance("test-service", ServiceInstance::new("test-service", "host2", 8080, "http"));
        
        let mut proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        // 启用缓存
        let cache_config = CacheConfig {
            enabled: true,
            strategy: CacheStrategy::TimeBasedCache { ttl: Duration::from_secs(60) },
            compress: false,
            serialize_format: "json".to_string(),
        };
        proxy = proxy.with_cache_config(cache_config);
        
        // 添加拦截器
        let req_interceptor = Arc::new(TestRequestInterceptor::new("workflow", 1));
        let resp_interceptor = Arc::new(TestResponseInterceptor::new("workflow", 1));
        proxy.add_request_interceptor(req_interceptor.clone()).await;
        proxy.add_response_interceptor(resp_interceptor.clone()).await;
        
        // 发送请求
        let request = Request::new("test-service", "GET", "/workflow-test");
        let result = proxy.call_with_retry(request).await;
        
        // 验证结果
        assert!(result.is_ok());
        assert_eq!(req_interceptor.get_execution_count(), 1);
        assert_eq!(resp_interceptor.get_execution_count(), 1);
        assert_eq!(transport.get_call_count(), 1);
        
        // 再次发送相同请求（应该使用缓存）
        let request2 = Request::new("test-service", "GET", "/workflow-test");
        let result2 = proxy.call_with_retry(request2).await;
        
        assert!(result2.is_ok());
        assert_eq!(req_interceptor.get_execution_count(), 2); // 拦截器仍然执行
        assert_eq!(resp_interceptor.get_execution_count(), 1); // 响应拦截器不执行（缓存命中）
        assert_eq!(transport.get_call_count(), 1); // 传输层不再调用
        
        // 检查最终统计
        let call_stats = proxy.get_call_stats().await;
        assert!(call_stats.total_calls >= 2);
        assert!(call_stats.successful_calls >= 2);
        assert_eq!(call_stats.failed_calls, 0);
        
        let service_stats = proxy.get_service_stats("test-service").await;
        assert!(service_stats.is_some());
        
        let (cache_total, cache_expired) = proxy.get_cache_stats().await;
        assert!(cache_total > 0);
        assert_eq!(cache_expired, 0);
    }

    #[tokio::test]
    async fn test_stress_concurrent_requests() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("stress-service", ServiceInstance::new("stress-service", "localhost", 8080, "http"));
        
        let proxy = Arc::new(create_test_proxy_with_mocks(registry, transport.clone()));
        
        // 发送大量并发请求
        let mut handles = Vec::new();
        for i in 0..50 {
            let proxy_clone = proxy.clone();
            let handle = tokio::spawn(async move {
                let request = Request::new("stress-service", "GET", &format!("/stress-{}", i));
                proxy_clone.call_with_retry(request).await
            });
            handles.push(handle);
        }
        
        // 等待所有请求完成
        let mut success_count = 0;
        let mut failure_count = 0;
        
        for handle in handles {
            match handle.await.unwrap() {
                Ok(_) => success_count += 1,
                Err(_) => failure_count += 1,
            }
        }
        
        // 并发控制可能导致部分请求失败，但大部分应该成功
        assert!(success_count > 40);
        assert!(success_count + failure_count == 50);
        
        // 验证统计信息
        let call_stats = proxy.get_call_stats().await;
        assert!(call_stats.total_calls >= 40);
    }

    #[tokio::test]
    async fn test_mixed_success_failure_scenarios() {
        let registry = Arc::new(MockAdvancedRegistry::new());
        let transport = Arc::new(MockAdvancedTransport::new());
        registry.add_instance("mixed-service", ServiceInstance::new("mixed-service", "localhost", 8080, "http"));
        
        let proxy = create_test_proxy_with_mocks(registry, transport.clone());
        
        // 添加错误拦截器
        let error_interceptor = Arc::new(TestResponseInterceptor::new("mixed", 1));
        proxy.add_response_interceptor(error_interceptor.clone()).await;
        
        // 成功请求
        let success_request = Request::new("mixed-service", "GET", "/success");
        let success_result = proxy.call_with_retry(success_request).await;
        assert!(success_result.is_ok());
        
        // 失败请求
        transport.set_should_fail(true);
        let failure_request = Request::new("mixed-service", "GET", "/failure");
        let failure_result = proxy.call_with_retry(failure_request).await;
        assert!(failure_result.is_err());
        
        // 验证统计
        assert_eq!(error_interceptor.get_execution_count(), 1); // 只有成功请求执行响应拦截器
        assert!(error_interceptor.get_error_count() >= 1); // 失败请求执行错误拦截器
        
        let call_stats = proxy.get_call_stats().await;
        assert!(call_stats.total_calls >= 2);
        assert!(call_stats.successful_calls >= 1);
        assert!(call_stats.failed_calls >= 1);
    }
}